import { createRouter, createWebHistory } from 'vue-router'
import { useNavigationStore } from '@/stores'

const routes = [
  // 一级路由
  // {
  // path: '/', component: () => import('@/views/ManageCom.vue'), redirect: '/home',
  // children: [
  //   { path: 'person', component: () => import('@/views/PersonCom.vue'), meta: { isAuth: true, title: '个人信息' } },
  //   { path: 'home', component: () => import('@/views/HomeCom.vue'), meta: { isAuth: true, title: '主页' } },
  //   { path: 'user', component: () => import('@/views/UserCom.vue'), meta: { isAuth: true, title: '用户管理' } },
  //   { path: 'file', component: () => import('@/views/FileCom.vue'), meta: { isAuth: true, title: '文件管理' } },
  //   { path: 'role', component: () => import('@/views/RoleCom.vue'), meta: { isAuth: true, title: '权限管理' } },
  //   { path: 'menu', component: () => import('@/views/MenuCom.vue'), meta: { isAuth: true, title: '菜单管理' } },
  //   { path: 'option', component: () => import('@/views/SystemCom.vue'), meta: { isAuth: true, title: '系统设置' } },
  //   { path: 'test', component: () => import('@/views/TestCom.vue'), meta: { isAuth: true, title: '系统测试' } }]
  // },
  { name: 'login', path: '/login', component: () => import('@/views/LoginCom.vue') },
  { name: 'register', path: '/register', component: () => import('@/views/registerCom.vue') },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})


// 注意 刷新页面会重置路由
export const setRouter = () => {
  // 拼装动态路由
  const manageRouter = { name: 'manage', path: '/', component: () => import('@/views/ManageCom.vue'), redirect: '/home', children: [{ name: 'person', path: 'person', component: () => import('@/views/PersonCom.vue'), meta: { isAuth: true, title: '个人信息' } }] }
  // 获取localStorage 里的userRouters
   const userRouters = localStorage.getItem('userRouter') ? JSON.parse(localStorage.getItem('userRouter')) : null
  // 处理之后存入 temp 中
  userRouters?.forEach(item => manageRouter.children.push({ path: item.path.substring(1).split('/')[0], component: () => import(`@/views/${item.vuePage}.vue`), meta: { isAuth: true, title: item.name } }))
  // 动态添加 添加路由
  router.addRoute(manageRouter)
}

// 防止刷新重置路由，再次添加路由
setRouter()


// 全局路由守卫
router.afterEach((to) => {
  // 跳转之后修改网页的面包屑
  const navigationStore = useNavigationStore()
  navigationStore.pageBreagCrumb = to.meta.title
})

export default router
